package com.anonymous.community.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

public class TokenManager {
    
    private static final String PREF_NAME = "anonymous_community_prefs";
    private static final String KEY_ACCESS_TOKEN = "access_token";
    private static final String KEY_REFRESH_TOKEN = "refresh_token";
    private static final String KEY_TOKEN_EXPIRY = "token_expiry";
    private static final String KEY_USER_ID = "user_id";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_USER_ROLE = "user_role";
    
    private SharedPreferences sharedPreferences;
    
    public TokenManager(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }
    
    /**
     * 保存登录token和用户信息
     */
    public void saveTokens(String accessToken, String refreshToken) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_ACCESS_TOKEN, accessToken);
        editor.putString(KEY_REFRESH_TOKEN, refreshToken);
        
        // 计算token过期时间（假设token有效期为1小时）
        long expiryTime = System.currentTimeMillis() + (60 * 60 * 1000); // 1小时后过期
        editor.putLong(KEY_TOKEN_EXPIRY, expiryTime);
        
        editor.apply();
    }
    
    /**
     * 保存用户信息
     */
    public void saveUserInfo(int userId, String username, String role) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(KEY_USER_ID, userId);
        editor.putString(KEY_USERNAME, username);
        editor.putString(KEY_USER_ROLE, role);
        editor.apply();
    }
    
    /**
     * 获取访问token
     */
    public String getAccessToken() {
        return sharedPreferences.getString(KEY_ACCESS_TOKEN, null);
    }
    
    /**
     * 静态方法：获取token（供ApiClient使用）
     */
    public static String getToken(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return prefs.getString(KEY_ACCESS_TOKEN, null);
    }
    
    /**
     * 静态方法：保存token
     */
    public static void saveToken(Context context, String token) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(KEY_ACCESS_TOKEN, token).apply();
    }
    
    /**
     * 静态方法：清除token
     */
    public static void clearToken(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        prefs.edit().clear().apply();
    }
    
    /**
     * 获取刷新token
     */
    public String getRefreshToken() {
        return sharedPreferences.getString(KEY_REFRESH_TOKEN, null);
    }
    
    /**
     * 获取用户ID
     */
    public int getUserId() {
        return sharedPreferences.getInt(KEY_USER_ID, -1);
    }
    
    /**
     * 获取用户名
     */
    public String getUsername() {
        return sharedPreferences.getString(KEY_USERNAME, null);
    }
    
    /**
     * 获取用户角色
     */
    public String getUserRole() {
        return sharedPreferences.getString(KEY_USER_ROLE, null);
    }
    
    /**
     * 检查是否有有效的token
     */
    public boolean hasValidToken() {
        String accessToken = getAccessToken();
        if (TextUtils.isEmpty(accessToken)) {
            return false;
        }
        
        // 检查token是否过期
        long expiryTime = sharedPreferences.getLong(KEY_TOKEN_EXPIRY, 0);
        return System.currentTimeMillis() < expiryTime;
    }
    
    /**
     * 检查token是否即将过期（提前5分钟刷新）
     */
    public boolean isTokenExpiringSoon() {
        long expiryTime = sharedPreferences.getLong(KEY_TOKEN_EXPIRY, 0);
        long fiveMinutesFromNow = System.currentTimeMillis() + (5 * 60 * 1000);
        return fiveMinutesFromNow >= expiryTime;
    }
    
    /**
     * 获取带Bearer前缀的Authorization header值
     */
    public String getAuthorizationHeader() {
        String accessToken = getAccessToken();
        if (!TextUtils.isEmpty(accessToken)) {
            return "Bearer " + accessToken;
        }
        return null;
    }
    
    /**
     * 清除所有token和用户信息（登出时使用）
     */
    public void clearTokens() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(KEY_ACCESS_TOKEN);
        editor.remove(KEY_REFRESH_TOKEN);
        editor.remove(KEY_TOKEN_EXPIRY);
        editor.remove(KEY_USER_ID);
        editor.remove(KEY_USERNAME);
        editor.remove(KEY_USER_ROLE);
        editor.apply();
    }
    
    /**
     * 更新访问token（刷新token时使用）
     */
    public void updateAccessToken(String newAccessToken) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_ACCESS_TOKEN, newAccessToken);
        
        // 重新计算过期时间
        long expiryTime = System.currentTimeMillis() + (60 * 60 * 1000); // 1小时后过期
        editor.putLong(KEY_TOKEN_EXPIRY, expiryTime);
        
        editor.apply();
    }
}